package com.servlet;

import com.bean.*;
import com.service.HwStuAttachService;
import com.service.HwStuService;
import com.service.impl.HwStuAttachServiceImpl;
import com.service.impl.HwStuServiceImpl;
import com.utils.DateUtils;
import com.utils.Page;
import com.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.utils.Page.PAGE_SIZE;

@WebServlet(name = "HwStuServlet", urlPatterns = "/HwStuServlet.do")
public class HwStuServlet extends BaseServlet {
    HwStuService hwStuService = new HwStuServiceImpl();
    HwStuAttachService hwStuAttachService = new HwStuAttachServiceImpl();

    protected void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String msg = null;
        Map<String, Object> map = new LinkedHashMap<>();
        Map<String, Object> data = new LinkedHashMap<>();
        map.put("code", 0);
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);
                //循环判断 每一个表单项 是普通类型 还是上传的文件
                for (FileItem fileItem : list) {
                    if (!fileItem.isFormField()) {
                        //上传的文件
                        String[] strings = fileItem.getName().split("\\.");
                        String type = "." + strings[strings.length - 1];
                        String imgName = System.currentTimeMillis() + type;
//                        fileItem.write(new File("E:\\hwmanage\\stuFile\\" + imgName));
                        fileItem.write(new File("D:\\Java\\Java2\\hwmanage\\stuFile\\" + imgName));
                        msg = "文件上传成功啦";
                        data.put("fileName", strings[0]);
                        data.put("url", imgName);
                        data.put("type", type);
                    }
                }
            } catch (Exception e) {
                msg = "文件上传失败啦QAQ";
            }
        } else {
            msg = "文件上传失败啦QAQ";
        }
        map.put("data", data);
        map.put("msg", msg);
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = null;
        Integer id = Integer.valueOf(request.getParameter("id"));

        HwStuAttach hwStuAttach=new HwStuAttach();
        hwStuAttach.setHwStuId(id);

        hwStuAttach = hwStuAttachService.selectBy(hwStuAttach);

        String url = hwStuAttach.getUrl();
        try {
//            String filePath = "E:\\hwmanage\\teaFile\\" + url;
            String filePath = "D:\\Java\\Java2\\hwmanage\\stuFile\\" + url;
            File file = new File(filePath);
            String FileName = hwStuAttach.getTitle()+hwStuAttach.getType();
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(FileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
            outputStream.close();
        }
    }
    protected void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HwStu hwStu = new HwStu();
        Map<String, Object> map = new LinkedHashMap<>();
        WebUtils.copyParamToBean(request.getParameterMap(), hwStu);
        hwStu.setCommentTime(DateUtils.getDate());
        int tip = hwStuService.updeteInfo(hwStu);
        String msg = "提交失败！";
        if (tip == 0) {
            map.put("tip", 1);
            msg = "提交成功！";
        }
        map.put("msg", msg);
        response.getWriter().write(WebUtils.parseJson(map));
    }
    protected void page(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        String content = request.getParameter("content");
        Page<HwStu> page = hwStuService.page(pageNo, pageSize, content);
        Map<String, Object> map = new LinkedHashMap<>(4);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Student student = (Student) request.getSession().getAttribute("user");
        HwStu hwStu = new HwStu();
        HwStuAttach hwStuAttach = new HwStuAttach();
        Map<String, Object> map = new LinkedHashMap<>();
        String msg = "提交作业失败啦！";
        WebUtils.copyParamToBean(request.getParameterMap(), hwStu);
        hwStu.setStatus(request.getParameter("title"));
        hwStu.setStudentId(student.getId());
        hwStu.setSubmitTime(DateUtils.getDate());
        int tip = hwStuService.insert(hwStu);
        if (tip == 0) {
            msg = "提交作业成功啦！";
            hwStu = hwStuService.selectBy(hwStu);
            hwStuAttach.setHwStuId(hwStu.getId());
            hwStuAttach.setTitle(request.getParameter("fileName"));
            WebUtils.copyParamToBean(request.getParameterMap(), hwStuAttach);
            tip = hwStuAttachService.insert(hwStuAttach);
            if (tip != 0) {
                msg = "提交作业的文件上传失败啦！";
                tip = 2;
            }
        }
        map.put("tip", tip);
        map.put("msg", msg);
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int tip = hwStuService.deleteById(id);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void approvedPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Student student = (Student) request.getSession().getAttribute("user");
        Integer id = student.getId();
        Page<HwStu> page = hwStuService.approved(id, pageNo, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }
}
